import React, { Component } from "react";
import "./style/style.less";
import { Avatar } from "antd";
import {
  SortableContainer,
  SortableElement,
  SortableHandle,
} from "react-sortable-hoc";
import {
  MenuOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons" ;
import TheButton from "@/components/TheButton";
import arrayMove from "array-move";
import TheDialog from "@/components/TheDialog";
import { apiGetShufflingList, apiGetShufflingSort, apiGetShufflingAdd, apiGetShufflingEdit, apiGetShufflingDel } from '@/request/configuration'
import Editor from "./component/editor";
import _ from 'lodash'
import _connect from '@/_connect'
const DragHandler = SortableHandle(() => (
  <TheButton  haspermi={['service:category:update']}  ><MenuOutlined style={{ cursor: "grab", color: "#999" }} /></TheButton>
  
));

const SortableItem = SortableElement(
  ({ value, onEdit, onDelete }) => {
    return (
      <div className={"category-card"}>
        {value.serviceClassifySort !== "1" && <DragHandler />}
        <div style={{ display: "flex", justifyContent: "flex-end" }}>
          <EditOutlined
            onClick={() => onEdit(value)}
            style={{ cursor: "pointer", position: "unset", marginRight: 15 }}
          />
          {value.serviceClassifySort !== "1" && <DeleteOutlined
            onClick={() => onDelete(value)}
            style={{ cursor: "pointer", position: "unset" }}
          />}
        </div>
        <div className={"category-content"}>
          <Avatar
            size={80}
            src={value.configCarouselFilez}
          />
          <span>{value.configCarouselTitle}</span>
        </div>
      </div>
    );
  }
);

const SortableList = SortableContainer(({ children }) => {
  return <>{children}</>;
});


class Category extends Component {
  state = {
    dataSource: [],
    mallData: [],
    title: "",
    dialogStatus: false,
    editValue: null,
    editMode: false,
    editType: "",
    btnLoading: false,
    classifyJson: "",
    len: 0
  };

  async componentDidMount() {
    await this.getData()
  }

  getData = async () => {
    const response = await apiGetShufflingList({ configCarouselSite: '10'});
    if (response.code === 0 && response.data.length !== 0 ) {
      const dataSource = response.data.filter((v, i) => v.configCarouselSort );
      const mallData = response.data.filter((v, i) => v.configCarouselSort === 1);
      this.setState({
        dataSource,
        mallData,
        len: response.data.length
      });
      this.onSortEnd({oldIndex:0,newIndex:0})
    }
  };
  onSortEnd = ({ oldIndex, newIndex }) => {
    this.setState(
      ({ dataSource }) => ({
        dataSource: arrayMove(dataSource, oldIndex, newIndex),
      }),
      () => {
        const dataSource = this.state.dataSource.map((v, i) => {
          delete v.createTime
          delete v.createUser
          delete v.updateTime
          delete v.updateUser
          return {
            ...v,
            configCarouselSort: i + 1,
          };
        });
        const classifyJson = dataSource;
        this.setState({
          dataSource,
          classifyJson,
        }, async () => {        
          await apiGetShufflingSort({ configCarousels: this.state.classifyJson })
          // this.getData()
        });
      }
    );
  };
  onEdit = (value, type) => {
    this.setState({
      dialogStatus: true,
      editValue: value,
      editType: "editor",
      title: '修改'
    });
  }; 
  onDelete = (value) => {
    React.$confirm({
      title: `您确定删除名称为${value.configCarouselTitle}的按钮吗？`,
      onOk: async () => {
        let res = await apiGetShufflingDel({ configCarouselId: value.configCarouselId })
        if(res.code === 0){
          let data = _.without(this.state.dataSource,value)
          this.setState({
            dataSource:data
          },()=>{
            this.onSortEnd({oldIndex:0,newIndex:0})
          })
        }
      },
    });
  };
  onAdd = () => {
    this.setState({
      dialogStatus: true,
      editValue: null,
      editType: 'add',
      title: '新增'
    });
  }
  dialogCancel = () => {
    this.setState({
      title: "",
      dialogStatus: false,
      editValue: null,
      editType: ''
    });
  };
  onFinish = async (value) => {
    const {  editValue,} = this.state
    const keys = Object.keys(value);
    const { editType } = this.state
    
    keys.forEach((v) => {
      if (!value[v]) {
        delete value[v];
      }
    });
    this.setState({
      btnLoading: true,
    });
    if (editType === 'add') {
      const res = await apiGetShufflingAdd({ ...value, configCarouselSite: '10', configCarouselSort: this.state.len + 1, configCarouselShowType:"0" })
      if (res.code === 0) {
        await this.getData();
        this.dialogCancel();
        React.$message({
          type: "info",
          content: "新增成功",
        });
        this.setState({
          btnLoading: false,
        });
      } else {
        this.setState({
          btnLoading: false,
        });
      }
    } else {
      console.log(value,'editvalue');
      const response = await apiGetShufflingEdit({ ...value,configCarouselId: editValue.configCarouselId,});
      if (response.code === 0) {
        await this.getData();
        this.dialogCancel();
        React.$message({
          type: "info",
          content: "修改成功",
        });
        this.setState({
          btnLoading: false,
        });
      } else {
        this.setState({
          btnLoading: false,
        });
      }
    }

  };

  render() {
    const {
      dataSource,
      editMode,
      editValue,
      dialogStatus,
      editType,
      btnLoading,
      title
    } = this.state;
    return (
      <div className={"p-layout-box category"}>
        <div className={"p-layout-content"}>
          <div
            style={{
              display: "flex",
              justifyContent: "flex-end",
              marginBottom: 30,
            }}
          >
            { dataSource.length < 15 &&
              <TheButton onClick={this.onAdd} haspermi={['shop:shopcategory:add']} size={"middle"} type={"default"} >
                新增
              </TheButton> 
            }
          </div>
          <SortableList onSortEnd={this.onSortEnd} axis={"xy"} useDragHandle>
            <div className={"category-card-box"}>
              {dataSource &&
                dataSource.map((v, i) => {
                  return (
                    <SortableItem
                      editMode={editMode}
                      onEdit={this.onEdit}
                      onDelete={this.onDelete}
                      index={i}
                      key={i}
                      value={v}
                    />
                  );
                })}
            </div>
          </SortableList>
          <TheDialog
            visible={dialogStatus}
            title={title}
            width={800}
            handleCancel={this.dialogCancel}
            footer={null}
          >
            <Editor dialogCancel={this.dialogCancel} onFinish={this.onFinish} data={editValue}
              btnLoading={btnLoading}
              type={editType}
              category={"button"}
              />
          </TheDialog>
        </div>
      </div>
    );
  }
}

export default _connect(Category);
